#include "stdafx.h"
#include "MMap.h"
#include <fstream>
using namespace std;

CMMap::CMMap()
{
}


CMMap::~CMMap()
{
}


void CMMap::LoadImg()
{
	char FileName[] = ".//img//map//sandTurn0.png";
	for (int i = 0; i < 7; i++)
	{
		sprintf_s(FileName, ".//img//map//sandTurn%d.png", i);
		m_SandImg[i] = cvLoadImage(FileName, 1);
	}
}


void CMMap::ReadMapTxt()
{
	fstream maptxt;
	maptxt.open(".//map//map_00_snake1.txt", ios::in);
	for (int i = 0; i < 15;i++)
	{
		for (int j = 0; j < 16;j++)
		{
			maptxt >> m_map[i][j];
		}
	}
	maptxt.close();
	maptxt.open(".//map//map_00_snake_Path.txt", ios::in);
	for (int i1 = 0; i1 < 15; i1++)
	{
		for (int j1 = 0; j1 < 16; j1++)
		{
			maptxt >> m_path[i1][j1];
		}
	}
	maptxt.close();

}


void CMMap::CreateBackImg()
{
	m_BackImg = cvCreateImage(cvSize(16 * 32, 15 * 32), IPL_DEPTH_8U, 3);
	cvSet(m_BackImg, cvScalar(255, 255, 255));
	int px=0;
	int py=0;
	for (int brow = 0; brow < 15;brow++)
	{
		px = 0;
		for (int bcol = 0; bcol < 16;bcol++)
		{
			if (m_map[brow][bcol] != -1)
			{
				if (m_map[brow][bcol] == 5)
				{
					m_Startb.x = bcol;
					m_Startb.y = brow;
				}
				if (m_map[brow][bcol] == 6)
				{
					m_Endb.x = bcol;
					m_Endb.y = brow;
				}
				IplImage* pimg = m_SandImg[m_map[brow][bcol]];
				for (int i = 0; i < pimg->height;i++)
				{
					for (int j = 0; j < pimg->width;j++)
					{
						CV_IMAGE_ELEM(m_BackImg,uchar,py+i,(px+j)*3+0) 
							= CV_IMAGE_ELEM(pimg, uchar, i, j * 3 + 0);
						CV_IMAGE_ELEM(m_BackImg, uchar, py + i, (px + j) * 3  + 1)
							= CV_IMAGE_ELEM(pimg, uchar, i, j * 3 + 1);
						CV_IMAGE_ELEM(m_BackImg, uchar, py + i, (px + j) * 3  + 2)
							= CV_IMAGE_ELEM(pimg, uchar, i, j * 3 + 2);
					}
				}
			}
			px += 32;
		}
		py += 32;
	}
}


int CMMap::GetDirectory(int posx, int posy)
{
	int blockx = posx / 32;
	int blocky = posy / 32;
	if (m_map[blocky][blockx] != 6)
	{
		return m_path[blocky][blockx];
	}
	return -1;
}


void CMMap::ReleaseMap()
{
	for (int i = 0; i < 7; i++)
	{
		cvReleaseImage(&m_SandImg[i]);

	}
	cvReleaseImage(&m_BackImg);

}


void CMMap::InitMap()
{
	LoadImg();
	ReadMapTxt();
	CreateBackImg();
}
